<template>
  <div class="app-container">
    <div class="query-area">
      <a-form
        :model="queryParams"
        ref="queryRef"
        layout="inline"
        v-show="showSearch"
        class="query-form"
      >
        <a-form-item label="有效状态" field="effectiveStatus">
          <a-select
            v-model="queryParams.effectiveStatus"
            placeholder="请选择有效状态"
            allow-clear
            style="width: 200px"
          >
            <a-option
              v-for="dict in is_effective"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </a-select>
        </a-form-item>
        <a-form-item label="创建时间" field="createTime">
          <a-date-picker
            allow-clear
            style="width: 200px"
            v-model="queryParams.createTime"
            value-format="YYYY-MM-DD"
            placeholder="请选择创建时间"
          >
          </a-date-picker>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" icon="Search" @click="handleQuery"
              >搜索</a-button
            >
            <a-button @click="resetQuery">重置</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </div>

    <div class="operation-area">
      <a-row class="operation-row">
        <a-space>
          <a-button type="primary" @click="handleAdd">新增</a-button>
          <a-button
            :disabled="multiple || includeEffective"
            @click="handleDelete"
            >删除</a-button
          >
        </a-space>
      </a-row>
    </div>

    <div class="table-area">
      <a-table
        class="custom-table"
        :loading="loading"
        :columns="columns"
        :data="unifyTestList"
        :row-selection="rowSelection"
        v-model:selected-keys="ids"
        row-key="id"
        @select="handleSelectionChange"
        @select-all="handleSelectAll"
        :pagination="{
          total: total,
          current: queryParams.pageNum,
          pageSize: queryParams.pageSize,
          showJumper: true,
          showTotal: true,
          showPageSize: true
        }"
        @page-change="tablePageChange"
        @page-size-change="tablePageSizeChange"
      >
        <template #effectiveStatus="{ record }">
          <dict-tag :options="is_effective" :value="record.effectiveStatus" />
        </template>
        <template #createTime="{ record }">
          <span>{{ parseTime(record.createTime, '{y}-{m}-{d}') }}</span>
        </template>
        <template #optional="{ record }">
          <a-space>
            <a-button
              type="text"
              status="warning"
              @click="handleUpdate(record, 'view')"
              >查看</a-button
            >
            <a-button type="text" status="warning" @click="handleUpdate(record)"
              >编辑</a-button
            >
            <a-button type="text" status="danger" @click="handleDelete(record)"
              >删除</a-button
            >
          </a-space>
        </template>
      </a-table>
    </div>

    <!-- 添加或编辑测试对话框 -->
    <a-modal
      :title="title"
      v-model:visible="open"
      unmount-on-close
      width="600px"
      title-align="start"
      :mask-closable="false"
    >
      <a-form
        ref="unifyTestRef"
        :model="form"
        :rules="rules"
        label-width="80px"
        :disabled="isDisabled"
      >
        <a-form-item label="富文本" field="name">
          <wang-editor v-model="form.name" :disabled="isDisabled"></wang-editor>
        </a-form-item>
        <a-form-item label="显示顺序" field="orderNum">
          <a-input v-model="form.orderNum" placeholder="请输入显示顺序" />
        </a-form-item>
        <a-form-item label="有效状态" field="effectiveStatus">
          <a-radio-group v-model="form.effectiveStatus">
            <a-radio
              v-for="dict in is_effective"
              :key="dict.value"
              :value="parseInt(dict.value)"
              >{{ dict.label }}</a-radio
            >
          </a-radio-group>
        </a-form-item>
      </a-form>
      <template #footer>
        <a-row justify="end">
          <a-space>
            <a-button @click="cancel">{{
              isDisabled ? '关闭' : '取消'
            }}</a-button>
            <a-button
              v-if="!isDisabled"
              type="primary"
              @click="submitForm"
              :loading="okLoading"
              >确定</a-button
            >
          </a-space>
        </a-row>
      </template>
    </a-modal>
  </div>
</template>

<script setup name="UnifyTest">
import {
  listUnifyTest,
  getUnifyTest,
  delUnifyTest,
  addUnifyTest,
  updateUnifyTest
} from '@/api/unify/unifyTest'
import { Modal, Message } from '@arco-design/web-vue'
const { proxy } = getCurrentInstance()
const { is_effective } = proxy.useDict('is_effective')
const unifyTestRef = ref(null)
const queryRef = ref(null)
const okLoading = ref(false)
const unifyTestList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
const isDisabled = ref(false)
const includeEffective = ref(false)
const rowSelection = reactive({
  type: 'checkbox',
  showCheckedAll: true,
  onlyCurrent: true
})
const columns = ref([
  {
    title: 'id',
    dataIndex: 'id'
  },
  {
    title: '富文本',
    dataIndex: 'name'
  },
  {
    title: '显示顺序',
    dataIndex: 'orderNum'
  },
  {
    title: '有效状态',
    slotName: 'effectiveStatus'
  },
  {
    title: '创建时间',
    slotName: 'createTime'
  },
  {
    title: '操作',
    slotName: 'optional',
    width: 200,
    align: 'center'
  }
])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    effectiveStatus: null,
    createTime: null
  },
  rules: {
    name: [{ required: true, message: '富文本不能为空', trigger: 'blur' }],
    orderNum: [
      { required: true, message: '显示顺序不能为空', trigger: 'blur' }
    ],
    effectiveStatus: [
      { required: true, message: '有效状态不能为空', trigger: 'change' }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询测试列表 */
function getList() {
  loading.value = true
  listUnifyTest(queryParams.value).then((response) => {
    unifyTestList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    orderNum: null,
    effectiveStatus: null,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  queryRef.value.resetFields()
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  queryRef.value.resetFields()
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  single.value = selection.length != 1
  multiple.value = !selection.length
  includeEffective.value = selection.reduce((result, currentValue) => {
    return result || currentValue?.effectiveStatus === 1
  }, false)
}

// 全选/取消全选
function handleSelectAll(checked) {
  if (checked) {
    ids.value = unifyTestList.value.map((i) => i.id)
  } else {
    ids.value = []
  }
  single.value = ids.value.length != 1
  multiple.value = !ids.value.length
}

// 分页变化
function tablePageChange(pageNum) {
  queryParams.value.pageNum = pageNum
  getList()
}

// 每页数据数量
function tablePageSizeChange(pageSize) {
  queryParams.value.pageSize = pageSize
  handleQuery()
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = '添加测试'
}

/** 编辑按钮操作 */
function handleUpdate(row, flag) {
  reset()
  const _id = row.id || ids.value
  getUnifyTest(_id).then((response) => {
    form.value = response.data
    open.value = true
    title.value = flag === 'view' ? '查看测试' : '编辑测试'
    isDisabled.value = flag === 'view'
  })
}

/** 提交按钮 */
function submitForm() {
  unifyTestRef.value.validate((valid) => {
    if (!valid) {
      okLoading.value = true
      if (form.value.id != null) {
        updateUnifyTest(form.value)
          .then((response) => {
            Message.success('编辑成功')
            open.value = false
            getList()
          })
          .finally(() => {
            okLoading.value = false
          })
      } else {
        addUnifyTest(form.value)
          .then((response) => {
            Message.success('新增成功')
            open.value = false
            getList()
          })
          .finally(() => {
            okLoading.value = false
          })
      }
    } else {
      const keys = Object.keys(valid)
      unifyTestRef.value.scrollToField(keys[0])
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  Modal.warning({
    title: '确认删除',
    content: '是否确认删除测试编号为"' + _ids + '"的数据项？',
    hideCancel: false,
    bodyStyle: { 'text-align': 'center' },
    onOk: () => {
      delUnifyTest(_ids).then((res) => {
        getList()
        Message.success('删除成功')
      })
    }
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    'unify/unifyTest/export',
    {
      ...queryParams.value
    },
    `unifyTest_${new Date().getTime()}.xlsx`
  )
}

getList()
</script>
